/**
 * Created by fangshufeng on 2018/2/27.
 */

import  React from 'react'

import EnvSelect from './EnvSelect'
import HeaderView from './HeaderView'
import BodyView from './BodyView'
import FooterView from './FooterView'
import QrCodeView from './QrCodeView'

import  {SuccessModal, ErrorModalAutoDismiss, SucceedModalAutoDismiss, InfoModal} from './AlertManage';

import io from 'socket.io-client'

import {
    Layout
} from 'antd';

const {Content} = Layout;

const Domain = 'http://192.168.33.22:7778';

export  default class MockHomeBuild extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            'currentEnv': null,
            'currentHost': null,
            'showView': this.envSelect(true),
            dataList: [],
            relationId:null
        };

        this.socketObj = null;
    }

    /**
     * 环境选择view
     * */
    envSelect = (firstSelect) => {

        return () => <EnvSelect onOk={(env, host) => {
            console.log('选择的环境是：', env, host);

            this.socketObj.emit('userSelectMockEnv', host);

            if (firstSelect) {
                this.setState({
                    showView: this.qrCodeView(env),
                    currentEnv: env,
                    currentHost: host
                })
            } else {

                this.setState({
                    showView: this.mainBodyView(),
                    currentEnv: env,
                    currentHost: host,
                    dataList: []
                })

            }

        }}/>
    };

    /**第二次选择过滤
     * */
    secondSelectEnv = () => {

        const tempModal = () => {
            InfoModal({
                title: '如果你的手机处于登录状态，请切换环境后重新登录！！！',
                onOk: () => {
                    this.setState({showView: this.envSelect(false)})
                }
            })
        }
        return () => <div>
            {tempModal()}
        </div>;
    };

    /**
     * 二维码view
     * */
    qrCodeView = (env) => {
        return () => <QrCodeView socketID={this.socketObj.id}
                                 currentEnv={env}
                                 reChange={() => this.setState({
                                     showView: this.envSelect(true)
                                 })}/>
    };

    /**
     * body
     * */
    mainBodyView = () => {
        return () => <BodyView dataSource={this.state.dataList}
                               clearClick={() => {
                                   this.setState({dataList: []});
                               }}
                               mockAction={(mockRespons, open) => {
                                   if (open) {
                                       if (mockRespons.mockValue === undefined) {
                                           ErrorModalAutoDismiss('数据不合法!!!');
                                           return;
                                       }
                                       this.socketObj.emit('mockDataMsg', mockRespons);
                                   } else {
                                       this.socketObj.emit('closeMock', mockRespons);
                                   }

                               }
                               }
        />

    };


    render() {
        return (
            <Layout className="layout">
                <HeaderView currentEnv={this.state.currentEnv}
                            relationId={this.state.relationId}
                            envChange={() => this.setState({
                                showView: this.secondSelectEnv()
                            })}/>
                <Content style={{
                    height: 700,
                    backgroundColor: 'white'
                }}>{this.state.showView()}</Content>
                <FooterView/>
            </Layout>
        );
    };

    componentDidMount() {

        this.socketObj = io.connect(Domain);
        this.socketObj.on('login', (socketID) => {
            console.log('连接成功会话ID为：', socketID);
            this.socketObj.id = socketID;
        });

        this.socketObj.on('message', (data) => {
            console.log('message', data);
            let temp = this.state.dataList;
            temp.unshift(data);
            this.setState({
                dataList: temp
            })
        });

        this.socketObj.on('registDevice', (succeed) => {

            console.log('设备注册成功');
            if (succeed) {
                SuccessModal('该设备注册成功！！！');
                this.setState({
                    showView: this.mainBodyView(),
                    relationId:this.socketObj.id
                });
            }
        });

        // socket.on('disconnect', (needRefresh) => {
        //     if (needRefresh) {
        //         this.setState({
        //             showQr: true
        //         });
        //     }
        // });
        //
        this.socketObj.on('mockSucced', (result) => {
            if (result) {
                SucceedModalAutoDismiss('mock成功，在对应设备重新请求即可生效', 3000)
                // this.setState({
                //     dataList: [],
                //     detailData: null
                // })
            } else {
                SucceedModalAutoDismiss('mock失败')
            }
        });

        this.socketObj.on('closeMockSucced', (result) => {
            if (result) {
                SucceedModalAutoDismiss('关闭mock成功！', 3000)
                // this.setState({
                //     dataList: [],
                //     detailData: null
                // })
            } else {
                SucceedModalAutoDismiss('关闭mock失败')
            }
        });
    }
}